var express = require("express");
var uunewid = require("uuid");
var router = express.Router();
var constants = require("../utils/constants");
const { checkProperty, checkEmpty, checkAuth } = require("../utils/utils");
const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_ASSETS";
const tagTableName = "SAP_JIANGDU_TAG_ASSETS";
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

var moment = require("moment");

router.get("/getAssetStatistics", function (req, res, next) {
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  getAssetStatistics().then(result => {
    res.send(result)
  })

})
async function getAssetStatistics() {
  let ohana_instance = new ohana(tableName);
  let result = await ohana_instance.raw(
    "select COMPANY_NAME, count(*) as TOTAL from " + tableName + " where COMPANY_NAME is not NULL group by COMPANY_NAME order by TOTAL desc  limit 5"
  );
  var resultData = {};
  resultData.topCompany = result;
  //monthly growth
  var dateQuery = "select count(*) as TOTAL from " + tableName + " where CREATED_AT between '" + moment().days(-30).format("YYYY-MM") + "' and '" + moment().format("YYYY-MM") + "'"
  console.log(dateQuery)
  var monthlygrowth = await ohana_instance.raw(dateQuery);
  resultData.monthlygrowth = monthlygrowth[0].TOTAL;
  return resultData;
}

router.get("/count", async (req, res, next) => {
  // #swagger.tags = ['设备']
  // #swagger.summary = '计数'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  let { USER_ID } = req.query;
  getCount(USER_ID)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function getCount(USER_ID) {
  let result = null;
  let ohana_instance = new ohana(tableName);
  if (USER_ID) {
    result = await ohana_instance.raw(
      "select count(*) as total from " +
      tableName +
      " where USER_ID_USER_ID = '" +
      USER_ID +
      "'"
    );
  } else {
    result = await ohana_instance.raw(
      "select count(*) as total from " + tableName
    );
  }
  return result[0];
}

router.post("/", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '获取asset'
  // #swagger.description = "获取设备列表以及搜索结果。1. 参数为空-> 所有已经发布的设备, 2. 获取已经发布单个设备 参数为： ASSET_ID Sample:{ASSET_ID:'xxxxx'},3搜索功能: 参数为 ASSET_NAME：''，获取个人创建的所有设备，需要添加type 为back"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset"
                    }  
                },
            }
    } */
  const userNew = checkAuth(req.user, constants.ASSETAUTH);
  const { data } = req.body;
  const { type } = req.body;
  const asset = new ohana(tableName); // new ohana('table_name');
  const { page } = req.body.data;
  //前段展示需要
  if (!type || userNew.admin == true) {
    // not search
    var condition = {};
    if (userNew.admin == false) {
      condition.STATUS = constants.STATUSON;
    }
    //非搜索
    if (!data.ASSET_NAME) {
      //有Asset_id 取 单个设备
      if (data.ASSET_ID) {
        condition.ASSET_ID = data.ASSET_ID;
        delete condition.STATUS;
        asset
          .findOne(condition)
          .then((result) => {
            if (result.length > 0) {
              if (
                result[0].COMPANY_NAME == userNew.company ||
                result[0].STATUS == constants.STATUSON
              ) {
                res.send(result);
              } else {
                res.send({
                  message: constants.MESSAGEWARNINGSTATUSOFF,
                  code: -1,
                });
              }
            } else {
              res.send({
                message: constants.MESSAGEWARNINGSTATUSOFF,
                code: -1,
              });
            }
          })
          .catch((err) => {
            log.error(err);
            res.status(500).send(err);
          });
      } else {
        //取所有 + 上分页逻辑
        var sqlText = "select * from " + tableName ;

        if (userNew.admin == false) {
          sqlText += " where STATUS = '" + constants.STATUSON + "'";
        }

        if (page) {
          const pageOffset = page.number * page.page;
          var pageText = " limit " + page.number + " offset " + pageOffset;
          sqlText += pageText;
        }
        // console.log(sqlText);
        asset.raw(sqlText)
          .then((result) => {
            res.send(result);
          })
          .catch((err) => {
            log.error(err);
            res.status(500).send(err);
          });
      }
    } else {
      //search
      var sqlText =
        "select * from " +
        tableName +
        " where ASSET_NAME like '%" +
        data.ASSET_NAME +
        "%'";
      //非管理员返回 状态为上架
      if (userNew.admin == false) {
        sqlText += " and STATUS = '" + constants.STATUSON + "'";
      }
      asset
        .raw(sqlText)
        .then((result) => {
          res.send(result);
        })
        .catch((err) => {
          log.error(err);
          res.status(500).send(err);
        });
    }
  } else if (type == constants.BACKEND && userNew.admin == false) {
    if (!data.ASSET_NAME) {
      //没有搜索 如果是子用户
      if (userNew.level == constants.LEVELTWO) {
        asset
          .find({ USER_ID_USER_ID: userNew.user_id })
          .then((result) => {
            res.send(result);
          })
          .catch((err) => {
            log.error(err);
            res.status(500).send(err);
          });
      } else {
        asset
          .find({ COMPANY_NAME: userNew.company })
          .then((result) => {
            res.send(result);
          })
          .catch((err) => {
            log.error(err);
            res.status(500).send(err);
          });
      }
    } else {
      // 有搜索 暂时不支持其他用户的 只能找当前用户
      var sqlText = "";
      if (userNew.level != constants.LEVELTWO) {
        sqlText =
          "select * from " +
          tableName +
          " where ASSET_NAME like '%" +
          data.ASSET_NAME +
          "%'" +
          " and COMPANY_NAME = '" +
          userNew.company +
          "'";
      } else {
        sqlText =
          "select * from " +
          tableName +
          " where ASSET_NAME like '%" +
          data.ASSET_NAME +
          "%'" +
          " and USER_ID_USER_ID = '" +
          userNew.user_id +
          "'";
      }
      asset
        .raw(sqlText)
        .then((result) => {
          res.send(result);
        })
        .catch((err) => {
          log.error(err);
          res.status(500).send(err);
        });
    }
  } else {
    res.sendStatus(500);
  }
});

router.post("/add", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '添加设备/需要有权限JWT。 没有为403. '
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset_add"
                    }  
                },
            }
    } */
  const { data } = req.body;
  data.ASSET_ID = uunewid.v4();
  data.CREATED_AT = moment().format("YYYY-MM-DD");
  data.UPDATED_AT = moment().format("YYYY-MM-DD");
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
    return;
  }
  // //看完权限之后检查必要的字段
  let checkResult = checkEmpty(constants.ASSETFIELDS, data);
  if (!checkResult.noUndefined && checkResult.noEmpty) {
    res.status(400).send({ message: checkResult.msg });
  }
  data.USER_ID_USER_ID = user.user_id;
  data.USER_NAME = user.user_name;
  if (!user.admin) {
    data.COMPANY_NAME = user.company ? user.company : "empty";
  }
  data.STATUS = constants.STATUSOFF; //创建 状态默认为off

  insertData(data)
    .then((result) => {
      if (result == 1) {
        res.status(200).send({ ASSET_ID: data.ASSET_ID });
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function insertData(body) {
  Object.keys(body).forEach((item) => {
    if (body[item] == ""||body[item]==null) delete body[item];
  });
  const user = new ohana(tableName); // new ohana('table_name');
  const result = await user.insert(body);
  return result;
}

/**
 * Get the company by criterian
 */
router.post("/search", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '搜索asset，query参数未知'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const queryData = req.query;
  const user = new ohana(tableName); // new ohana('table_name');
  if (queryData == null) {
    user
      .find()
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    user
      .find(queryData)
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
});

/**update Assets  */
router.put("/", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '修改asset'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset_update"
                    }  
                },
            }
    } */
  //   checkData(res, req.body.data)
  const { data } = req.body;
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
    return;
  }
  delete data.tags;
  updateAsset(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.delete("/", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '删除asset'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset_delete"
                    }  
                },
            }
    } */
  const { data } = req.body;
  deleteAsset(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function updateAsset(body) {
  const asset = new ohana(tableName); // new ohana('table_name');
  const result = await asset.update(
    {
      ASSET_ID: body.ASSET_ID,
    },
    body
  );
  return result;
}
async function deleteAsset(body) {
  const asset = new ohana(tableName);
  try {
    const result = await asset.raw(
      "delete from " + tableName + " where ASSET_ID = '" + body.ASSET_ID + "'"
    );
    asset.raw(
      "delete from " +
      constants.RECOMMENDLISTTABLE +
      " where RECOMMENDED_ID ='" +
      body.ASSET_ID +
      "'"
    );
    asset.raw(
      "delete from " +
      constants.FAVORITETABLE +
      " where FAVOURITE_ID ='" +
      body.ASSET_ID +
      "'"
    );
    return result;
  } catch (error) {
    log.error(error);
    return -1;
  }
}

/// Asset tags

router.post("/AssetTags", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '获取标签'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset_tag"
                    }  
                },
            }
    } */
  const { data } = req.body;
  getAssetTag(data)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.post("/addTags", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '增加标签'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset_tag_add_delete"
                    }  
                },
            }
    } */
  const { data } = req.body;
  insertAssetData(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else if (result == -1) {
        res.status(200).send({ code: -1, message: "请勿重复点击" })
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.post("/deleteTags", function (req, res, next) {
  // #swagger.tags = ['设备']
  // #swagger.summary = '删除标签'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/asset_tag_add_delete"
                    }  
                },
            }
    } */
  const { data } = req.body;
  deletaAssetTag(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

/**
 * 127.0.0.1:4000/api/users/CompanyInfo
 * @param {*} body
 * @returns
 */
async function getAssetTag(data) {
  const assetTag = new ohana(tagTableName); // new ohana('table_name');
  const result = await assetTag.raw(
    'select "TAG_ID", "TAG_NAME","TAG_VALUE" ,"TAG_CATEGORY" from "SAP_JIANGDU_TAGS" where "TAG_ID" in (Select "TAG_ID_TAG_ID" from "' +
    tagTableName +
    '" where "ASSET_ID_ASSET_ID" = \'' +
    data.ASSET_ID +
    "' )"
  );
  return result;
}
async function insertAssetData(data) {
  const assetTag = new ohana(tagTableName); // new ohana('table_name');
  const resultNum = await assetTag.find(data);
  if (resultNum.length > 0) {
    return -1;
  }
  const result = await assetTag.insert(data);
  return result;
}
async function deletaAssetTag(data) {
  const assetTag = new ohana(tagTableName); // new ohana('table_name');
  const result = await assetTag.raw(
    'delete from "' +
    tagTableName +
    "\" where ASSET_ID_ASSET_ID = '" +
    data.ASSET_ID_ASSET_ID +
    "' and TAG_ID_TAG_ID = '" +
    data.TAG_ID_TAG_ID +
    "'"
  );
  return result;
}

module.exports = router;
